<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="modelValue"
    @close="closeForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ standard.opera === "add" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar class="ba-table-form-scrollbar">
      <div
        class="ba-operate-form ba-add-form"
        :style="'width: calc(100% - ' + state.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="onAddSubmit(formRef)"
          :model="state.form"
          label-position="right"
          label-width="160px"
          :rules="rules"
        >
          <el-form-item label="巡检标准id" prop="groupId">
            <el-input v-model="state.form.groupId" disabled />
          </el-form-item>
          <el-form-item label="检查项目名称" prop="name">
            <el-input v-model="state.form.name" />
          </el-form-item>
          <!-- <FormItem
            label="记录方式"
            v-model="state.form.type"
            type="radio"
            prop="type"
            :data="{
              content: {
                0: '单选',
                1: '数字',
                2: '文本',
              },
              childrenAttr: { border: true },
            }"
          /> -->
          <el-form-item label="结果选项" prop="option">
            <el-input v-model="state.form.option" />
          </el-form-item>
          <el-form-item label="标准状态图片">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :headers="headerConfig"
              list-type="picture-card"
              :limit="1"
              name="avatarfile"
              :on-change="changUpload"
              :on-remove="handleRemove"
              :auto-upload="false"
              :http-request="handleUplodFile"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <div class="imgBox" style="margin-left: 10px">
              <el-image
                style="width: 148px; height: 148px"
                :src="state.form!.photo"
                fit="fill"
                :preview-src-list="[ state.form!.photo]"
              />
            </div>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="state.form.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              @keyup.enter.stop=""
              placeholder="备注"
            />
          </el-form-item>
        </el-form></div
    ></el-scrollbar>
    <template #footer>
      <div :style="'width: calc(100% - ' + state.labelWidth / 1.8 + 'px)'">
        <el-button @click="closeForm">取消</el-button>
        <el-button
          v-blur
          :loading="state.submitLoading"
          @click="onAddSubmit(formRef)"
          type="primary"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadUserFile,
  UploadInstance,
  UploadRequestOptions,
  UploadFile,
  UploadFiles,
} from "element-plus";
// import { useDictionary } from "@/store/backend/tool/dictionary";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { ElNotification } from "element-plus"; //处理导航信息
import { _download, _upload } from "@/utils/axios";
import { useStandard } from "@/store/backend/LineCruiseM/standard";
import { useStandardItems } from "@/store/backend/LineCruiseM/items";

const { proxy } = useCurrentInstance(); //mitt
const formRef = ref<FormInstance>();
// const dict = useDictionary();
const standard = useStandard();
const items = useStandardItems();

const state: {
  labelWidth: number;
  submitLoading: boolean;
  form: any;
  host: string;
} = reactive({
  labelWidth: 160,
  submitLoading: false,
  form: {},
  host: "",
});

// 标准图片
const fileList = ref<UploadUserFile[]>([]);
const realUploadFile = ref<UploadUserFile[]>([]);

const headerConfig = {
  Authorization: JSON.parse(localStorage.getItem("adminInfo") as any)?.token,
};

//移除标准图片
const handleRemove: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  const { uid } = uploadFile;
  const selectFileList = fileList.value.filter((item) => {
    return item.uid != uid;
  });
  fileList.value = selectFileList;
};
//标准图片文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUpload: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles[0].raw);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.png|.jpg|.jpeg$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.png|.jpg|.jpeg",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //将上传的设备图片信息存入列表
  fileList.value.push(uploadFile);
  realUploadFile.value = [];
  let formData = new FormData();
  formData.append("file", uploadFiles[0].raw as any); //添加文件对象
  formData.append("name", "photo");
  _upload("/common/upload", formData, "").then((res: any) => {
    console.log("将上传的设备图片信息存入列表", res);
    // baTable.form.items!.pic = res.data.url;
    state.form!.photo =
      state.host === "" ? res.data.url : state.host + res.data.fileName;
  });
};

//允许自行实现上传文件的请求 再用户触发了realSubmit后触发
const handleUplodFile = (options: UploadRequestOptions) => {
  console.log("允许自行实现上传文件的请求", options);
  realUploadFile.value.push(options.file);
  let formData = new FormData();
  formData.append("file", options.file); //添加文件对象
  formData.append("name", "phpte");
  // _upload("/common/upload", formData, "").then((res: any) => {
  //   state.form.pic = res.data.url;
  //   //上传完设备图片再上传pdf
  //   uploadPdfRef.value!.submit();
  // });
};

interface Props {
  modelValue: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
});

const emits = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
}>();
const closeForm = () => {
  emits("update:modelValue", false);
};

const rules = reactive<FormRules>({
  name: [{ required: true, message: "检查项目名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "记录方式不能为空", trigger: "blur" }],
  option: [{ required: true, message: "结果选项不能为空", trigger: "blur" }],
});

const onAddSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      state.form.type = state.form.type - 0; //type为number类型
      console.log("提交", state.form);
      if (standard.opera === "edit") {
        items.editStandardSet(state.form).then((res) => {
          closeForm();
          proxy.eventBus.emit("refreshStandard");
        });
      } else {
        //新增
        items.addStandardSet(state.form).then((res) => {
          closeForm();
          proxy.eventBus.emit("refreshStandard");
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

//获取域名进行拼接
const getBaseUrl = () => {
  let url = window.location;
  console.log("获取域名进行拼接", url.origin, url.origin.includes("s"));
  if (url.origin.includes("180")) {
    //https
    state.host = url.origin;
  } else {
    state.host = "";
  }
};
getBaseUrl();

proxy.eventBus.on("editStandardSet", (data: any) => {
  state.form = data;
  console.log("state.form", data);
});
proxy.eventBus.on("addStandardSet", (data: any) => {
  state.form.groupId = data.id;
  console.log("state.form", data);
});
onMounted(() => {
  // state.form = dict.item;
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
</style>
